Page({
  data: {
    searchKey: '',
    book: null,
    addresses: [],
    myAddresses: [],
    searched: false,
    showSelector: false
  },

  onSearchInput(e) {
    this.setData({
      searchKey: e.detail.value
    });
  },

  async handleSearch() {
    const { searchKey } = this.data;
    if (!searchKey) {
      wx.showToast({
        title: '请输入搜索内容',
        icon: 'none'
      });
      return;
    }

    try {
      const cloud = getApp().globalData.cloud;
      if (!cloud) {
        throw new Error('云环境未初始化');
      }

      wx.showLoading({
        title: '搜索中...',
        mask: true
      });

      const db = cloud.database();
      const _ = db.command;
      
      const { data } = await db.collection('books')
        .where(_.or([
          {
            name: db.RegExp({
              regexp: searchKey,
              options: 'i',
            })
          },
          {
            isbn: searchKey
          }
        ]))
        .limit(1)
        .get();

      wx.hideLoading();

      if (data && data.length > 0) {
        this.setData({ 
          book: data[0],
          searched: true
        });
        this.loadBookAddresses(data[0]._id);
      } else {
        this.setData({ 
          book: null,
          addresses: [],
          searched: true
        });
        wx.showToast({
          title: '查无此书',
          icon: 'none',
          duration: 2000
        });
      }
    } catch (err) {
      wx.hideLoading();
      console.error('搜索失败：', err);
      
      this.setData({
        book: null,
        addresses: [],
        searched: true
      });

      wx.showToast({
        title: '搜索失败',
        icon: 'error'
      });
    }
  },

  async loadBookAddresses(bookId) {
    try {
      const cloud = getApp().globalData.cloud;
      const db = cloud.database();
      
      // 获取当前用户的 openid
      const { result } = await cloud.callFunction({
        name: 'getOpenId'
      });
      
      // 只获取所有地址记录，但标记是否是当前用户的
      const { data } = await db.collection('bookAddresses')
        .where({
          bookId: bookId
        })
        .get();
      
      // 标记哪些是当前用户的地址
      const addresses = data.map(item => ({
        ...item,
        isMine: item._openid === result.openid
      }));
        
      this.setData({
        addresses: addresses || []
      });
    } catch (err) {
      console.error('加载地址失败：', err);
      this.setData({
        addresses: []
      });
    }
  },

  // 显示地址选择器
  showAddressSelector() {
    this.loadMyAddresses();
  },

  // 隐藏地址选择器
  hideAddressSelector() {
    this.setData({ showSelector: false });
  },

  // 防止穿透
  preventTouchMove() {
    return;
  },

  // 加载我的地址列表
  async loadMyAddresses() {
    try {
      const cloud = getApp().globalData.cloud;
      const db = cloud.database();
      
      // 获取当前用户的 openid
      const { result } = await cloud.callFunction({
        name: 'getOpenId'
      });
      
      // 只查询当前用户创建的地址
      const { data } = await db.collection('addresses')
        .where({
          _openid: result.openid  // 只获取当前用户的地址
        })
        .get();

      // 先设置地址数据
      this.setData({ 
        myAddresses: data || []
      });

      // 如果用户没有地址，显示提示并不显示选择器
      if (!data || data.length === 0) {
        wx.showToast({
          title: '请先添加地址',
          icon: 'none',
          duration: 2000
        });
        // 可以选择直接跳转到添加地址页面
        wx.navigateTo({
          url: '/pages/user/address/edit/edit'
        });
      } else {
        // 只有当有地址时才显示选择器
        this.setData({ 
          showSelector: true
        });
      }
    } catch (err) {
      console.error('加载我的地址失败：', err);
      wx.showToast({
        title: '加载地址失败',
        icon: 'error'
      });
    }
  },

  // 选择地址并添加到书籍下
  async selectAddress(e) {
    const addressId = e.currentTarget.dataset.id;
    const { book } = this.data;
    
    try {
      const cloud = getApp().globalData.cloud;
      const db = cloud.database();
      
      // 检查是否已添加过该地址
      const { data } = await db.collection('bookAddresses')
        .where({
          bookId: book._id,
          addressId: addressId
        })
        .get();

      if (data && data.length > 0) {
        wx.showToast({
          title: '该地址已添加',
          icon: 'none'
        });
        return;
      }

      // 获取地址详情
      const addressRes = await db.collection('addresses')
        .doc(addressId)
        .get();
      
      const address = addressRes.data;

      // 获取用户 openid
      const { result } = await cloud.callFunction({
        name: 'getOpenId'
      });

      // 添加关联记录
      await db.collection('bookAddresses').add({
        data: {
          bookId: book._id,
          addressId: addressId,
          phone: address.phone,
          remark: address.remark,
          createTime: new Date().toLocaleString(),
          _openid: result.openid  // 添加用户标识
        }
      });

      wx.showToast({
        title: '添加成功',
        icon: 'success'
      });

      // 刷新地址列表
      this.loadBookAddresses(book._id);
      // 关闭选择器
      this.hideAddressSelector();

    } catch (err) {
      console.error('添加地址失败：', err);
      wx.showToast({
        title: '添加失败',
        icon: 'error'
      });
    }
  },

  // 跳转到添加地址页面
  goToAddAddress() {
    wx.navigateTo({
      url: '/pages/user/address/edit/edit'
    });
  },

  // 删除地址
  async handleDeleteAddress(e) {
    const { id } = e.currentTarget.dataset;
    const { book } = this.data;
    
    try {
      const cloud = getApp().globalData.cloud;
      const db = cloud.database();

      // 确认删除
      const { confirm } = await wx.showModal({
        title: '确认删除',
        content: '确定要删除这个地址吗？',
        confirmText: '删除',
        confirmColor: '#ff0000'
      });

      if (!confirm) return;

      // 删除记录
      await db.collection('bookAddresses').doc(id).remove();

      wx.showToast({
        title: '删除成功',
        icon: 'success'
      });

      // 刷新地址列表
      this.loadBookAddresses(book._id);

    } catch (err) {
      console.error('删除地址失败：', err);
      wx.showToast({
        title: '删除失败',
        icon: 'error'
      });
    }
  }
}); 